package com.beidouin.GnssMain.sample;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beidouin.GnssMain.EventSerialReceive;
import com.beidouin.GnssMain.models.PilotInfo;
import com.beidouin.GnssMain.R;

import java.util.ArrayList;
import java.util.TimeZone;


public class MainMenu extends SerialPortActivity {

    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;
    private static final int UNIT_SPEED_MPS = 0;
    private static final int UNIT_SPEED_KMPH = 1;
    private static final int UNIT_SPEED_KNOTS = 2;


    protected final String TAG = this.getClass().getName() + "@" + this.hashCode();
	TextView latlongTextView, localeTypeTextView,
            heightTextView, velocityTextView, satelliteTextView, dateTextView,
            timeTextView, dopTextView, latlongDirection, velocityTextView2,
            velocityDirection, timeIndicateTextView;
    RelativeLayout latlongRelative,
            heightRelative, velocityRelative, satelliteRelative,
            timeRelative, dopRelative;

    public int speedUnitSel;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initBottomView();
        getPersimmions();

        activityType = 0;
//        // generate fake data when port is down
//        generateFakeData();
        speedUnitSel = UNIT_SPEED_MPS;
        navigationImage.setImageResource(R.drawable.navigation_selected);
        navigationText.setTextColor(getResources().getColor(R.color.app_main));
        latlongTextView = (TextView) findViewById(R.id.latlong);
        localeTypeTextView = (TextView) findViewById(R.id.localeType);
        heightTextView = (TextView) findViewById(R.id.heightTv);
        velocityTextView = (TextView) findViewById(R.id.velocityTv);
        satelliteTextView = (TextView) findViewById(R.id.satelliteTv);
        timeTextView = (TextView) findViewById(R.id.timeText);
        dateTextView = (TextView) findViewById(R.id.dateText);
        dopTextView = (TextView) findViewById(R.id.dopText);
        latlongDirection = (TextView) findViewById(R.id.latlongdirect);
        velocityDirection = (TextView) findViewById(R.id.velocityDirection); //速度上面的单位指示
        velocityTextView2 = (TextView) findViewById(R.id.velocityTv2); //速度方向
        timeIndicateTextView = (TextView) findViewById(R.id.timeIndicateTextView);

        latlongRelative = (RelativeLayout) findViewById(R.id.latlongrl);
        heightRelative = (RelativeLayout) findViewById(R.id.heightrl);
        velocityRelative = (RelativeLayout) findViewById(R.id.verlocityrl);
        timeRelative = (RelativeLayout) findViewById(R.id.timerl);
        latlongRelative.setOnClickListener(transUnit);
        heightRelative.setOnClickListener(transUnit);
        velocityRelative.setOnClickListener(transUnit);
        timeRelative.setOnClickListener(transUnit);
        validateUI();
    }

    View.OnClickListener transUnit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RelativeLayout target =  (RelativeLayout)v;
            switch (target.getId()) {
                case R.id.latlongrl:
                    if(latlongDirection.getText().toString().equals("度分")){
                        latlongDirection.setText("度分秒");
                        setLatlongTextView(2);
                    }else if(latlongDirection.getText().toString().equals("度分秒")){
                        latlongDirection.setText("度");
                        setLatlongTextView(0);
                    }else if(latlongDirection.getText().toString().equals("度")){
                        latlongDirection.setText("度分");
                        setLatlongTextView(1);
                    }

                    break;
                case R.id.verlocityrl:
                    String speed = "";
                    if(speedUnitSel == UNIT_SPEED_MPS){
                        speedUnitSel = UNIT_SPEED_KMPH;
                        speed = String.format("%.2f km/h", PilotInfo.getInstance().getVelocity() * 1.852f);
                        velocityTextView.setText(speed);
                    }else if(speedUnitSel == UNIT_SPEED_KMPH){
                        speedUnitSel = UNIT_SPEED_KNOTS;
                        speed = String.format("%.2f knots", PilotInfo.getInstance().getVelocity());
                        velocityTextView.setText(speed);
                    }else {
                        speedUnitSel = UNIT_SPEED_MPS;
                        speed = String.format("%.2f m/s", PilotInfo.getInstance().getVelocity() * 0.5144f);
                        velocityTextView.setText(speed);
                    }
                    break;
                case R.id.timerl:
                    //xingsiyu modified
                    if(timeIndicateTextView.getText().toString().equals("GMT+8")){
                        timeIndicateTextView.setText("GMT");
                        timeTextView.setText(PilotInfo.getInstance().getTime());
                        dateTextView.setText(PilotInfo.getInstance().getDate());
                        Log.e("tttt","========="+PilotInfo.getInstance().getTime());

                    }else{
                        timeIndicateTextView.setText("GMT+8");
                        timeTextView.setText(PilotInfo.getInstance().changeTimeToUTC());
                        dateTextView.setText(PilotInfo.getInstance().changeDateToUTC());
                        Log.e("tttt","========="+PilotInfo.getInstance().changeTimeToUTC());
                    }
                    break;

            }
        }
    };

    private void validateUI(){
        if(latlongDirection.getText().toString().equals("度分")){
            setLatlongTextView(1);
        }else if(latlongDirection.getText().toString().equals("度分秒")){
            setLatlongTextView(2);
        }else if(latlongDirection.getText().toString().equals("度")){
            setLatlongTextView(0);
        }
        //xingsiyu modified
        String speed = "";
        if(speedUnitSel == UNIT_SPEED_MPS){
            speed = String.format("%.02f m/s", PilotInfo.getInstance().getVelocity() * 0.5144f);
            velocityTextView.setText(speed);
        }else if(speedUnitSel == UNIT_SPEED_KMPH){
            speed = String.format("%.02f km/h", PilotInfo.getInstance().getVelocity() * 1.852f);
            velocityTextView.setText(speed);
        }else {
            speed = String.format("%.02f knots", PilotInfo.getInstance().getVelocity());
            velocityTextView.setText(speed);;
        }

        localeTypeTextView.setText(PilotInfo.getInstance().getLocateType());
        heightTextView.setText(PilotInfo.getInstance().getAltitude());
     //   velocityTextView.setText(PilotInfo.getInstance().getVelocityStr());
        velocityTextView2.setText(PilotInfo.getInstance().getVelocityOrientation());
        satelliteTextView.setText(PilotInfo.getInstance().getTotalSatelliteNumber());
        //display time, xingsiyu modified
        if(timeIndicateTextView.getText().toString().equals("GMT")){
            timeTextView.setText(PilotInfo.getInstance().getTime());
            dateTextView.setText(PilotInfo.getInstance().getDate());
            if(timeTextView.getText()=="")////////如果无数据，显示N/A
            {
                timeTextView.setText("N/A");
                dateTextView.setText("N/A");
            }
        }else{
            timeTextView.setText(PilotInfo.getInstance().changeTimeToUTC());
            dateTextView.setText(PilotInfo.getInstance().changeDateToUTC());
            if(timeTextView.getText()=="")////////如果无数据，显示N/A
            {
                timeTextView.setText("N/A");
                dateTextView.setText("N/A");
            }
        }

        dopTextView.setText(PilotInfo.getInstance().getDop());
    }

    private void setLatlongTextView(int level){
        latlongTextView.setText(PilotInfo.getInstance().transLat(level, "latitude") +
                PilotInfo.getInstance().getLatitudeUnit() + "/" + PilotInfo.getInstance().transLat(level, "longitude") +
                PilotInfo.getInstance().getLongitudeUnit());
    }

    protected Activity getCurrentActivity(){
        return MainMenu.this;
    }

    private void generateFakeData(){
        String s = "$GNGGA,051724.00,4003.98492797,N,11614.76685598,E,1,10,2.132,42.70178,M,,M,,*58\n" +
                "$GPGSA,A,3,3,6,28,,,,,,,,,,3.187,2.132,2.369*3C\n" +
                "$BDGSA,A,3,101,102,103,104,106,107,110,,,,,,3.187,2.132,2.369*17\n" +
                "$GPGSV,3,1,10,28,77,186,47,17,57,315,26,1,35,48,,3,46,102,44*42\n" +
                "$GPGSV,3,2,10,22,38,71,,11,22,64,,19,35,294,,6,27,236,43*44\n" +
                "$GNRMC,073454.00,A,4003.95135868,N,11614.77230588,E,0.000,0.000,020916,,E,A*05";
        String[] mList = s.split("\r\n");
        //this function is not usable
     //   PilotInfo.getInstance().populatePilotInfo(mList);
    }


    public void onEventMainThread(final EventSerialReceive event)
    {
        runOnUiThread(new Runnable() {
            public void run() {
            if (event.eventType == EventSerialReceive.EVENT_UPDATE_ACTIVITY) { //data from serial port
                if ((event.iData & EventSerialReceive.UPDATE_MAIN) != 0) {
                    validateUI();
                }
            }
            }
        });
    }


    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}
